<?php

namespace App\Queue;

use App\Utility\Pool\RedisPool;
use EasySwoole\Component\Pool\PoolManager;
use EasySwoole\EasySwoole\Logger;
use Swoole\Coroutine\Redis;
use EasySwoole\EasySwoole\Config;

class Queue
{
    private $redis;
    private $queue;
    private $queuePrefix = 'queue:';
    function __construct(){
        $options = Config::getInstance()->getConf('redis');
        $redis = PoolManager::getInstance()
            ->getPool(RedisPool::class)
            ->getObj($options['pool_time_out']);
        if ($redis) {
            $this->redis = $redis;
            $this->queue = $this->queuePrefix.$options['queue'];
        } else {
            //直接抛给异常处理，不往下
            throw new \Exception('error,Redis Pool is Empty');
        }
    }

    public function __destruct(){
        PoolManager::getInstance()->getPool(RedisPool::class)->recycleObj($this->redis);
    }

    public function onQueue($queue)
    {
        $this->queue = $this->queuePrefix.$queue;
        return $this;
    }

    //入列
    function push($data){
        return $this->redis->lpush($this->queue, json_encode($data));
    }
    //出列
    function read(){
        return json_decode($this->redis->rPop($this->queue),false);
    }


}